package jp.tyas.libs.lisp;

import java.lang.reflect.*;
import java.util.*;

public class ProxyDef extends Hashtable
{
  static ClassLoader sLoader = ProxyDef.class.getClassLoader();
  Class[] mInterfaces;

  class ProxyMember extends Hashtable implements InvocationHandler {
    ProxyMember(Hashtable members) {
      super(members);
    }
    public Object invoke(Object proxy, Method method, Object[] args) {
      Callee c = (Callee)get(method);
      if (c == null)
        return null;
      List l = Builtin.newList();
      l.add(getProxyThis(proxy));
      if (args != null)
        l.addAll(Arrays.asList(args));
      return c.invoke(l, null);
    }
  }

  public ProxyDef(Class[] interfaces) {
    super();
    mInterfaces = interfaces;
  }

  public ProxyDef(Class[] interfaces, Hashtable members) {
    super(members);
    mInterfaces = interfaces;
  }

  public Object newInstance() {
    return Proxy.newProxyInstance(sLoader, mInterfaces, new ProxyMember(this));
  }

  public static Hashtable getProxyThis(Object proxy) {
    return (ProxyMember)Proxy.getInvocationHandler(proxy);
  }
}
